<?php
/**
 * 文章编辑页面功能类
 *
 * @package DeepSeekAISummarizer
 * @since 3.7.2
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 防止重复声明类
if (!class_exists('DeepSeekAI_Post_Editor')) {

class DeepSeekAI_Post_Editor {
    
    private $plugin;
    
    // 构造与初始化
    /**
     * 构造函数，注册所有文章编辑页面的钩子
     */
    public function __construct($plugin) {
        $this->plugin = $plugin;
        
        // 加载样式和脚本
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        
        // 在文章编辑页面添加元框
        add_action('add_meta_boxes', array($this, 'add_meta_boxes'));
        
        // 保存文章时的钩子
        add_action('save_post', array($this, 'save_post_meta'));
        
        // 文章密码相关的AJAX
        add_action('wp_ajax_deepseek_ai_save_post_password', array($this, 'ajax_save_post_password'));
        add_action('wp_ajax_deepseek_ai_remove_post_password', array($this, 'ajax_remove_post_password'));
    }

    /**
     * 为文章编辑页面加载脚本和样式
     */
    public function enqueue_admin_scripts($hook) {
        // 检查是否在文章编辑页面
        if (in_array($hook, array('post.php', 'post-new.php'))) {
            // 加载样式
            wp_enqueue_style('deepseek-ai-admin', DEEPSEEK_AI_PLUGIN_URL . 'css/style.css', array(), $this->plugin->get_version());
            
            // 加载WordPress媒体库（用于图片上传）
            wp_enqueue_media();
            
            // 加载脚本
            wp_enqueue_script('deepseek-ai-admin', DEEPSEEK_AI_PLUGIN_URL . 'js/scripts.js', array('jquery'), $this->plugin->get_version(), true);
            
            // 本地化脚本
            wp_localize_script('deepseek-ai-admin', 'deepseek_ai_ajax', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('deepseek_ai_nonce'),
                'generating_text' => '正在生成中...',
                'error_text' => '生成失败，请检查API设置',
                'plugin_url' => DEEPSEEK_AI_PLUGIN_URL,
                'version' => $this->plugin->get_version(),
                'plugin_name' => 'DeepSeek AI 文章摘要生成器',
                'debug_enabled' => $this->plugin->is_debug_enabled(),
                'debug_level' => $this->plugin->get_debug_level()
            ));
        }
    }
    
    // 元框与保存
    public function add_meta_boxes() {
        add_meta_box(
            'aiqiji-summary-generator',
            '爱奇吉智能摘要',
            array($this, 'meta_box_callback'),
            'post',
            'normal',
            'high'  // 提高优先级
        );
    }
    
    public function meta_box_callback($post) {
        wp_nonce_field('deepseek_ai_meta_box', 'deepseek_ai_meta_box_nonce');
        
        // 优先使用WordPress原生摘要
        $summary = get_the_excerpt($post);
        
        // 如果原生摘要为空，则尝试使用自定义字段
        if (empty($summary)) {
            $summary = get_post_meta($post->ID, '_deepseek_ai_summary', true);
        }
        
        $seo_title = get_post_meta($post->ID, '_deepseek_ai_seo_title', true);
        $seo_description = get_post_meta($post->ID, '_deepseek_ai_seo_description', true);
        $seo_keywords = get_post_meta($post->ID, '_deepseek_ai_seo_keywords', true);
        
        echo '<div class="deepseek-ai-meta-box">';
        
        // 添加LOGO头部
        echo '<div class="deepseek-ai-header" style="display: flex; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #ddd;">';
        echo '<img src="' . plugin_dir_url(dirname(__FILE__)) . 'img/logo.svg" alt="爱奇吉智能摘要"  />';
        echo '<h2 style="margin: 0; color: #4D6BFE; font-size: 18px; font-weight: 600;">爱奇吉智能摘要</h2>';
        echo '</div>';
        
        // 摘要部分
        echo '<div class="deepseek-ai-section">';
        echo '<h3><i class="dashicons dashicons-format-aside"></i> 文章摘要</h3>';
        echo '<div class="deepseek-ai-controls">';
        echo '<button type="button" class="deepseek-ai-btn summary" id="generate-summary">生成摘要</button>';
        echo '<div class="deepseek-ai-loading" id="summary-loading" style="display:none;">正在生成摘要...</div>';
        echo '</div>';
        echo '<textarea name="deepseek_ai_summary" id="deepseek-ai-summary" rows="4" style="width:100%;">' . esc_textarea($summary) . '</textarea>';
        echo '<p class="description">摘要将同步到WordPress原生摘要字段，兼容所有主题</p>';
        echo '</div>';
        
        // SEO部分
        echo '<div class="deepseek-ai-section">';
        echo '<h3><i class="dashicons dashicons-search"></i> SEO 优化</h3>';
        echo '<div class="deepseek-ai-controls">';
        echo '<button type="button" class="deepseek-ai-btn summary" id="generate-seo">生成SEO内容</button>';
        echo '<div class="deepseek-ai-loading" id="seo-loading" style="display:none;">正在生成SEO内容...</div>';
        echo '</div>';
        
        echo '<div class="deepseek-ai-seo-fields">';
        echo '<p><label for="deepseek-ai-seo-title">SEO标题:</label></p>';
        echo '<input type="text" name="deepseek_ai_seo_title" id="deepseek-ai-seo-title" value="' . esc_attr($seo_title) . '" style="width:100%;" />';
        echo '<p class="description">用于搜索引擎显示的标题，建议包含关键词</p>';
        
        echo '<p><label for="deepseek-ai-seo-description">SEO描述:</label></p>';
        echo '<textarea name="deepseek_ai_seo_description" id="deepseek-ai-seo-description" rows="3" style="width:100%;">' . esc_textarea($seo_description) . '</textarea>';
        echo '<p class="description">用于搜索引擎显示的描述，建议150字以内</p>';
        
        echo '<p><label for="deepseek-ai-seo-keywords">关键词:</label></p>';
        echo '<input type="text" name="deepseek_ai_seo_keywords" id="deepseek-ai-seo-keywords" value="' . esc_attr($seo_keywords) . '" style="width:100%;" placeholder="关键词1, 关键词2, 关键词3" />';
        echo '<p class="description">用逗号分隔的关键词列表，建议3-5个关键词</p>';
        echo '</div>';
        
        echo '</div>';
        
        // 社交标签部分
        $social_title = get_post_meta($post->ID, '_deepseek_ai_social_title', true);
        $social_description = get_post_meta($post->ID, '_deepseek_ai_social_description', true);
        $social_image = get_post_meta($post->ID, '_deepseek_ai_social_image', true);
        $wechat_image = get_post_meta($post->ID, '_deepseek_ai_wechat_image', true);
        
        echo '<div class="deepseek-ai-section">';
        echo '<h3><i class="dashicons dashicons-share"></i> 社交媒体标签</h3>';
        echo '<p class="description">设置在社交媒体平台分享时显示的内容</p>';
        
        echo '<div class="deepseek-ai-social-fields">';
        echo '<p><label for="deepseek-ai-social-title">社交分享标题:</label></p>';
        echo '<input type="text" id="deepseek-ai-social-title" value="' . esc_attr($social_title) . '" style="width:100%;" placeholder="留空则使用SEO标题或文章标题" />';
        echo '<p class="description">用于社交媒体分享的标题，如微信、微博等</p>';
        
        echo '<p><label for="deepseek-ai-social-description">社交分享描述:</label></p>';
        echo '<textarea id="deepseek-ai-social-description" rows="3" style="width:100%;" placeholder="留空则使用SEO描述或文章摘要">' . esc_textarea($social_description) . '</textarea>';
        echo '<p class="description">用于社交媒体分享的描述，建议简洁有吸引力</p>';
        
        echo '<p><label for="deepseek-ai-social-image">通用社交分享图片:</label></p>';
        echo '<div class="deepseek-ai-image-upload">';
        echo '<input type="hidden" id="deepseek-ai-social-image" value="' . esc_attr($social_image) . '" />';
        echo '<div class="image-preview" id="social-image-preview">';
        if ($social_image) {
            echo '<img src="' . esc_url($social_image) . '" style="max-width: 200px; height: auto; border: 1px solid #ddd; border-radius: 4px;" />';
        }
        echo '</div>';
        echo '<button type="button" class="deepseek-ai-upload-btn" id="upload-social-image">选择图片</button>';
        echo '<button type="button" class="deepseek-ai-remove-btn" id="remove-social-image"' . ($social_image ? ' style="margin-left: 10px;"' : ' style="margin-left: 10px; display:none;"') . '>移除图片</button>';
        echo '<p class="description">推荐尺寸: 1200x630px，用于Facebook、Twitter等平台</p>';
        echo '</div>';
        
        echo '<p><label for="deepseek-ai-wechat-image">微信分享专用图片:</label></p>';
        echo '<div class="deepseek-ai-image-upload">';
        echo '<input type="hidden" id="deepseek-ai-wechat-image" value="' . esc_attr($wechat_image) . '" />';
        echo '<div class="image-preview" id="wechat-image-preview">';
        if ($wechat_image) {
            echo '<img src="' . esc_url($wechat_image) . '" style="max-width: 200px; height: auto; border: 1px solid #ddd; border-radius: 4px;" />';
        }
        echo '</div>';
        echo '<button type="button" class="deepseek-ai-upload-btn" id="upload-wechat-image">选择图片</button>';
        echo '<button type="button" class="deepseek-ai-remove-btn" id="remove-wechat-image"' . ($wechat_image ? ' style="margin-left: 10px;"' : ' style="margin-left: 10px; display:none;"') . '>移除图片</button>';
        echo '<p class="description">推荐尺寸: 300x300px，使用标准Open Graph格式(og:image)，微信会自动识别</p>';
        echo '</div>';
        
        echo '<div class="deepseek-ai-controls" style="margin-top: 20px;">';
        echo '<button type="button" class="deepseek-ai-btn social" id="save-social-settings" data-post-id="' . $post->ID . '">保存</button>';
        echo '<div class="deepseek-ai-loading" id="social-loading" style="display:none;">正在保存...</div>';
        echo '</div>';
        
        // 文章访问密码设置
        $password_set = get_post_meta($post->ID, '_deepseek_ai_password_hash', true) ? true : false;
        echo '<div class="deepseek-ai-section">';
        echo '<h3><i class="dashicons dashicons-lock"></i> 文章访问密码</h3>';
        echo '<input type="password" id="deepseek_ai_post_password" name="deepseek_ai_post_password" value="" placeholder="留空不修改" autocomplete="new-password" style="width:200px;" />';
        echo '<button type="button" class="button" id="save-post-password" style="margin-left:10px;">确定</button>';
        echo '<button type="button" class="button" id="remove-post-password" style="margin-left:10px;">取消密码访问</button>';
        echo '<span id="post-password-status" style="margin-left:10px;color:green;display:none;">操作成功</span>';
        if ($password_set) {
            echo '<span style="color:green;margin-left:10px;">已设置</span>';
        } else {
            echo '<span style="color:gray;margin-left:10px;">未设置</span>';
        }
        echo '<p class="description">如设置，将覆盖全局密码。密码加密存储，无法反查。</p>';
        ?>
        <script type="text/javascript">
        jQuery(document).ready(function($){
            $('#save-post-password').on('click', function(){
                var pwd = $('#deepseek_ai_post_password').val();
                if(pwd === ''){ alert('请输入新密码'); return; }
                var data = {
                    action: 'deepseek_ai_save_post_password',
                    post_id: <?php echo intval($post->ID); ?>,
                    password: pwd,
                    _ajax_nonce: '<?php echo wp_create_nonce('deepseek_ai_save_post_password'); ?>'
                };
                $.post(ajaxurl, data, function(resp){
                    if(resp.success){
                        $('#post-password-status').show().delay(1500).fadeOut();
                        $('#deepseek_ai_post_password').val('');
                        location.reload();
                    }else{
                        alert('保存失败');
                    }
                });
            });
            $('#remove-post-password').on('click', function(){
                if(!confirm('确定要取消该文章的密码访问吗？')) return;
                var data = {
                    action: 'deepseek_ai_remove_post_password',
                    post_id: <?php echo intval($post->ID); ?>,
                    _ajax_nonce: '<?php echo wp_create_nonce('deepseek_ai_remove_post_password'); ?>'
                };
                $.post(ajaxurl, data, function(resp){
                    if(resp.success){
                        $('#post-password-status').show().delay(1500).fadeOut();
                        location.reload();
                    }else{
                        alert('操作失败');
                    }
                });
            });
        });
        </script>
        <?php
        echo '</div>';
        
        // 版权信息
        echo '<div class="deepseek-ai-copyright" style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-left: 4px solid #007cba; border-radius: 4px;">';
        echo '<p style="margin: 0; color: #666; font-size: 13px; line-height: 1.5;">';
        echo '<i class="dashicons dashicons-info" style="color: #007cba; margin-right: 5px;"></i>';
        echo '本插件由 <strong>爱奇吉</strong> 开发，基于 AI 技术提供智能内容生成服务。';
        echo '<br>如有问题或建议，请访问 <a href="https://www.aiqji.cn/contact" target="_blank" style="color: #007cba; text-decoration: none;">官方网站</a> 或联系技术支持。';
        echo '</p>';
        echo '</div>';
        
        echo '</div>';
         echo '</div>';
         echo '</div>';
    }
    
    public function save_post_meta($post_id) {
        if (!isset($_POST['deepseek_ai_meta_box_nonce']) || !wp_verify_nonce($_POST['deepseek_ai_meta_box_nonce'], 'deepseek_ai_meta_box')) {
            return;
        }
        
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // 保存摘要
        if (isset($_POST['deepseek_ai_summary'])) {
            $summary = sanitize_textarea_field($_POST['deepseek_ai_summary']);
            // 更新WordPress原生摘要字段
            wp_update_post(array(
                'ID' => $post_id,
                'post_excerpt' => $summary
            ));
            // 更新自定义字段（使用update_post_meta确保只保存一次）
            update_post_meta($post_id, '_deepseek_ai_summary', $summary);
        }
        
        // 保存SEO数据
        if (isset($_POST['deepseek_ai_seo_title'])) {
            update_post_meta($post_id, '_deepseek_ai_seo_title', sanitize_text_field($_POST['deepseek_ai_seo_title']));
        }
        
        if (isset($_POST['deepseek_ai_seo_description'])) {
            update_post_meta($post_id, '_deepseek_ai_seo_description', sanitize_textarea_field($_POST['deepseek_ai_seo_description']));
        }
        
        if (isset($_POST['deepseek_ai_seo_keywords'])) {
            update_post_meta($post_id, '_deepseek_ai_seo_keywords', sanitize_text_field($_POST['deepseek_ai_seo_keywords']));
        }
        
        // 保存文章访问密码
        if (isset($_POST['deepseek_ai_post_password']) && $_POST['deepseek_ai_post_password'] !== '') {
            $password_hash = password_hash(sanitize_text_field($_POST['deepseek_ai_post_password']), PASSWORD_DEFAULT);
            update_post_meta($post_id, '_deepseek_ai_password_hash', $password_hash);
        }
        
        // 社交标签数据现在通过AJAX手动保存，不再自动保存
    }

    // AJAX相关
    public function ajax_save_post_password() {
        check_ajax_referer('deepseek_ai_save_post_password');
        $post_id = intval($_POST['post_id']);
        if (!current_user_can('edit_post', $post_id)) {
            wp_send_json_error('无权限');
        }
        $pwd = isset($_POST['password']) ? sanitize_text_field($_POST['password']) : '';
        if ($pwd === '') {
            wp_send_json_error('密码不能为空');
        }
        update_post_meta($post_id, '_deepseek_ai_password_hash', password_hash($pwd, PASSWORD_DEFAULT));
        wp_send_json_success();
    }
    
    public function ajax_remove_post_password() {
        check_ajax_referer('deepseek_ai_remove_post_password');
        $post_id = intval($_POST['post_id']);
        if (!current_user_can('edit_post', $post_id)) {
            wp_send_json_error('无权限');
        }
        delete_post_meta($post_id, '_deepseek_ai_password_hash');
        wp_send_json_success();
    }
}

} // end if (!class_exists('DeepSeekAI_Post_Editor')) 